/*
 * Droplet.cpp
 *
 * Created: 5/11/2012 4:13:57 PM
 *  Author: common
 */ 
#define F_CPU 32000000UL

#include <avr/io.h>
#include <math.h>
#include <util/delay.h>

#include "motor.h"
#include "RGB_LED.h"
#include "pc_com.h"
#include "RGB_sensor.h"
#include "power.h"


void Config32MHzClock(void)
{
	// initialize clock source to be 32MHz internal oscillator (no PLL)
	CCP = CCP_IOREG_gc;							//Security Signature to modify clock
	OSC.CTRL = OSC_RC32MEN_bm;					// enable internal 32MHz oscillator
	while(!(OSC.STATUS & OSC_RC32MRDY_bm));		// wait for oscillator ready
	CCP = CCP_IOREG_gc;							//Security Signature to modify clock
	CLK.CTRL = 0x01;							//select sysclock 32MHz osc
}

int main(void)
{
	Config32MHzClock();
	
	motor_init();
	RGB_LED_init();
	pc_com_init();
	
	char i = 0;
	
	printf("Press any key to pause/unpause. \r\n");
	
	set_blue_led(50);
	_delay_ms(500);
	led_off();
	
	while (1)
	{
		if (PC_USART.STATUS & USART_RXCIF_bm)
		{
			i = PC_USART.DATA;
			printf("\r\nPaused (%c) \r\n", i);
			while (!(PC_USART.STATUS & USART_RXCIF_bm));	
			i = PC_USART.DATA;
		}

		printf("%c  ", ++i % 26 + 'A');
		
		for (uint8_t j = 0; j < 5; j++)
		{
			set_red_led(40);
			_delay_ms(100);
			led_off();
			_delay_ms(900);
		}
		set_green_led(40);
		_delay_ms(500);
		led_off();
		
		uint8_t duty_cycle = 192;
		TCC0_CCA = TCC0_CCB = duty_cycle;
		TCC1_CCA = TCC1_CCB = duty_cycle;
		TCE0_CCA = TCE0_CCB = duty_cycle;

			TCC1.CTRLB = TC1_CCAEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCC1.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);
			TCC0.CTRLB = TC0_CCAEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCC0.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);
			TCE0.CTRLB = TC0_CCAEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCE0.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);

		set_red_led(40); _delay_ms(100); led_off(); _delay_ms(500);
		
			TCC1.CTRLB = TC1_CCBEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCC1.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);
			TCC0.CTRLB = TC0_CCBEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCC0.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);
			TCE0.CTRLB = TC0_CCBEN_bm | TC_WGMODE_SS_gc; _delay_ms(500); TCE0.CTRLB = TC_WGMODE_SS_gc; _delay_ms(500);
		
		_delay_ms(1000);
		stop();
		
	}	
}